package com.envmonitor.interfaces.rest;

import com.envmonitor.application.service.DeviceApplicationService;
import com.envmonitor.domain.model.Device;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/devices")
@RequiredArgsConstructor
public class DeviceController {
    
    private final DeviceApplicationService deviceApplicationService;
    
    @GetMapping
    public ResponseEntity<List<Device>> getAllDevices() {
        return ResponseEntity.ok(deviceApplicationService.getAllDevices());
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<Device> getDeviceById(@PathVariable Long id) {
        return deviceApplicationService.getDeviceById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    @GetMapping("/type/{type}")
    public ResponseEntity<List<Device>> getDevicesByType(@PathVariable Device.DeviceType type) {
        return ResponseEntity.ok(deviceApplicationService.getDevicesByType(type));
    }
    
    @PostMapping
    public ResponseEntity<Device> createDevice(@Valid @RequestBody Device device) {
        return new ResponseEntity<>(deviceApplicationService.createDevice(device), HttpStatus.CREATED);
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<Device> updateDevice(@PathVariable Long id, @Valid @RequestBody Device device) {
        return deviceApplicationService.updateDevice(id, device)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteDevice(@PathVariable Long id) {
        deviceApplicationService.deleteDevice(id);
        return ResponseEntity.noContent().build();
    }
    
    @PutMapping("/{id}/toggle")
    public ResponseEntity<Device> toggleDeviceStatus(@PathVariable Long id) {
        return deviceApplicationService.toggleDeviceStatus(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
}